#include <rtthread.h>
#include <rtdevice.h>
#include "klibc/kerrno.h"
#include "offline.h"
#include "rtdef.h"
#include "rttypes.h"
#include "sbus.h"
#include "robotdef.h"


#define LOG_TAG              "SBUS"
#define LOG_LVL              LOG_LVL_DBG
#include <ulog.h>

#define SBUS_UART_NAME       "uart3"      /* 串口设备名称 */

/* 串口接收消息结构 */
struct rx_msg
{
    rt_device_t dev;
    rt_size_t size;
};
/* 串口设备句柄 */
static rt_device_t serial;
/* 初始化配置参数 */
struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;  
/* 指向信号量的指针 */
static rt_sem_t sbus_sem = RT_NULL;


/* 接收数据回调函数 */
static rt_err_t sbus_recv(rt_device_t dev, rt_size_t size)
{
    rt_err_t result =RT_EOK;
    rt_device_read(dev,-1,&sbus.SBUS_CH.SBUS_DATA,size);

    if (sbus.SBUS_CH.SBUS_DATA[0] == 0x0F && size == 25 && sbus.SBUS_CH.SBUS_DATA[24] == 0x00)
    {
        if (sbus_sem != RT_NULL)
        {
            rt_sem_release(sbus_sem);
        }
    }
    return result;
}

static void serial_thread_entry(void *parameter)
{
    rt_err_t result;
    while (1)
    {
        result = rt_sem_take(sbus_sem,RT_WAITING_FOREVER);
        if (result==RT_EOK)
        {
            update_sbus(sbus.SBUS_CH.SBUS_DATA);
        }
        rt_thread_mdelay(5);
    }
}

int sbus_thread_entry_init(void)
{
    rt_err_t ret = RT_EOK;

    /* 创建一个动态信号量，初始值是 0 */
    sbus_sem = rt_sem_create("sbus_sem", 0, RT_IPC_FLAG_PRIO);
    if (sbus_sem == RT_NULL)
    {
        LOG_E("create dynamic semaphore failed.\n");
        return -1;
    }

    /* 查找串口设备 */
    serial = rt_device_find(SBUS_UART_NAME);
    if (!serial)
    {
        LOG_E("find %s failed!\n", SBUS_UART_NAME);
        return RT_ERROR;
    }

    config.baud_rate=100000;
    config.data_bits=DATA_BITS_8;
    config.stop_bits=STOP_BITS_2;
    config.parity=PARITY_EVEN;
    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);

    /* 以 DMA 接收及轮询发送方式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_RDWR |RT_DEVICE_FLAG_RX_NON_BLOCKING | RT_DEVICE_FLAG_TX_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, sbus_recv);

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("sbus", serial_thread_entry, RT_NULL, 1024, 15, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    sbus.SBUS_CH.ConnectState =0X0C;
    sbus.offline_manage_init.event =OFFLINE_SBUS;
    sbus.offline_manage_init.enable = OFFLINE_ENABLE;
    sbus.offline_manage_init.error_level = OFFLINE_ERROR_LEVEL;
    sbus.offline_manage_init.beep_times  = BEEP_DISABLE;
    sbus.offline_manage_init.offline_time =100;

    offline_event_init(sbus.offline_manage_init);

    LOG_D("sbus thread init success!\n");

    return ret;
}
#if defined (GIMBAL_BOARD) && CONTROL_SOURCE == 1
INIT_APP_EXPORT(sbus_thread_entry_init);
#endif

